package com.flydust.apipulse.service;

import com.flydust.apipulse.entity.Endpoint;
import com.flydust.apipulse.entity.HealthCheckResult;
import com.flydust.apipulse.repository.EndpointRepository;
import com.flydust.apipulse.repository.HealthCheckResultRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

@Service
public class HealthCheckService {

    @Autowired
    private EndpointRepository endpointRepository;

    @Autowired
    private HealthCheckResultRepository healthCheckResultRepository;

    // 每分钟执行一次健康检查
    @Scheduled(fixedRate = 60000)
    public void performHealthChecks() {
        List<Endpoint> endpoints = endpointRepository.findAll();
        for (Endpoint endpoint : endpoints) {
            checkEndpoint(endpoint);
        }
    }

    public void checkEndpoint(Endpoint endpoint) {
        HealthCheckResult result = new HealthCheckResult();
        result.setEndpoint(endpoint);
        
        try {
            URL url = new URL(endpoint.getUrl());
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod(endpoint.getMethod());
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);
            
            long startTime = System.currentTimeMillis();
            int responseCode = connection.getResponseCode();
            long endTime = System.currentTimeMillis();
            
            boolean success = responseCode == endpoint.getExpectedStatus();
            
            result.setSuccess(success);
            result.setStatusCode(responseCode);
            result.setResponseTime(endTime - startTime);
            
            if (!success) {
                result.setErrorMessage("Expected status " + endpoint.getExpectedStatus() + " but got " + responseCode);
            }
        } catch (IOException e) {
            result.setSuccess(false);
            result.setErrorMessage(e.getMessage());
        }
        
        healthCheckResultRepository.save(result);
    }
}